package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.DialogInterface;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.dialog.ECAlertDialog;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.listeners.IRecyclerViewItemLongListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.MyPartnerAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.RecyclerViewUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 好友
 * Created by Administrator on 2016/11/28.
 */

public class MyPartnersActivity extends BaseChatActivity implements ICommonViewUi, IRecyclerViewItemLongListener, LoadMoreClickListener, SwipeRefreshLayout.OnRefreshListener {

    @InjectView(R.id.group_by_tv)
    TextView groupByTv;
    @InjectView(R.id.search_layout)
    RelativeLayout searchLayout;

    @OnClick(R.id.group_by_select_layout)
    public void onSelectLayoutClick() {
        if (selectLayout.getVisibility() == View.VISIBLE) {
            selectLayout.setVisibility(View.GONE);
        } else {
            selectLayout.setVisibility(View.VISIBLE);
        }
    }

    @InjectView(R.id.select_layout)
    LinearLayout selectLayout;

    @InjectView(R.id.defalut_select_img)
    ImageView defalutSelectImg;
    @InjectView(R.id.defalut_select_tv)
    TextView defalutSelectTv;
    @InjectView(R.id.default_layout)
    LinearLayout defaultLayout;
    @InjectView(R.id.name_select_img)
    ImageView nameSelectImg;
    @InjectView(R.id.name_select_tv)
    TextView nameSelectTv;
    @InjectView(R.id.name_layout)
    LinearLayout nameLayout;
    @InjectView(R.id.gender_select_img)
    ImageView genderSelectImg;
    @InjectView(R.id.gender_select_tv)
    TextView genderSelectTv;
    @InjectView(R.id.gender_layout)
    LinearLayout genderLayout;
    @InjectView(R.id.country_select_img)
    ImageView countrySelectImg;
    @InjectView(R.id.country_select_tv)
    TextView countrySelectTv;
    @InjectView(R.id.country_layout)
    LinearLayout countryLayout;
    @InjectView(R.id.age_select_img)
    ImageView ageSelectImg;
    @InjectView(R.id.age_select_tv)
    TextView ageSelectTv;
    @InjectView(R.id.age_layout)
    LinearLayout ageLayout;
    @InjectView(R.id.language_select_img)
    ImageView languageSelectImg;
    @InjectView(R.id.language_select_tv)
    TextView languageSelectTv;
    @InjectView(R.id.language_layout)
    LinearLayout languageLayout;
    String orderBy = "";
    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<UserInfo> mResultList = new ArrayList<UserInfo>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    String accountName = "";
    String descAsc="";

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_member;
    }

    @Override
    protected void initViewsAndEvents() {
        setTitle("My Partners");
        accountName = getIntent().getStringExtra("account");
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);

        searchLayout.setVisibility(View.GONE);

        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();
        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new MyScrollListener());

        refreshListView();

        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
    }

    public void refreshListView() {

        MyPartnerAdapter mIntermediary = new MyPartnerAdapter(mContext, mResultList, this);

        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {

            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }


    @Override
    public void toRequest(int eventTag) {
        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "100");
            map.put("accountName", accountName);
            map.put("orderBy", orderBy);
            map.put("descAsc",descAsc);
            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.FRIEND_LIST, map);

        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "100");
            map.put("accountName", accountName);
            map.put("orderBy", orderBy);
            map.put("descAsc",descAsc);
            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.FRIEND_LIST, map);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //下拉刷新

            List<UserInfo> resultList = parseResult(result);

            mResultList.clear();
            mResultList.addAll(resultList);
            List<ECContacts> contacts = new ArrayList<>();
            for (int i = 0; i < resultList.size(); i++) {
                ECContacts contact = new ECContacts();
                UserInfo info = mResultList.get(i);
                StringBuffer message = new StringBuffer();
                message.append("{\"result\":");
                message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
                message.append("\"nickName\":\"" + info.getNickName() + "\",");
                message.append("\"id\":\"" + info.getId() + "\",");
                message.append("\"gender\":\"" + info.getGender() + "\",");
                message.append("\"age\":\"" + info.getAge() + "\",");
                message.append("\"country\":\"" + info.getCountry() + "\",");
                message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
                message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
                contact.setNickname(mResultList.get(i).getNickName() + "(" + message.toString() + ")");
                contact.setContactid(mResultList.get(i).getAccountName());
                contacts.add(contact);
            }
            ContactSqlManager.insertContacts(contacts);
            refreshListView();


        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            List<UserInfo> resultList = parseResult(result);

            mResultList.addAll(resultList);
            List<ECContacts> contacts = new ArrayList<>();
            for (int i = 0; i < resultList.size(); i++) {
                ECContacts contact = new ECContacts();
                UserInfo info = mResultList.get(i);
                StringBuffer message = new StringBuffer();
                message.append("{\"result\":");
                message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
                message.append("\"nickName\":\"" + info.getNickName() + "\",");
                message.append("\"id\":\"" + info.getId() + "\",");
                message.append("\"gender\":\"" + info.getGender() + "\",");
                message.append("\"age\":\"" + info.getAge() + "\",");
                message.append("\"country\":\"" + info.getCountry() + "\",");
                message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
                message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
                contact.setNickname(mResultList.get(i).getNickName() + "(" + message.toString() + ")");
                contact.setContactid(mResultList.get(i).getAccountName());
                contacts.add(contact);
            }
            ContactSqlManager.insertContacts(contacts);
            adapter.notifyDataSetChanged();
        }else if(eventTag==ApiConstants.EventTags.FRIEND_DEL){
            onRefresh();
        }
    }

    /**
     * 解析结果
     *
     * @param result
     * @return
     */
    public List<UserInfo> parseResult(String result) {
        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                UserInfo.class);
        return dataParser.getDatas(
                result, "list");
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;
        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void onItemClick(int position) {
        UserInfo info = mResultList.get(position);
        ECContacts mContacts = ContactSqlManager.getCacheContact(info.getId());
        if (mContacts == null) {
            mContacts = new ECContacts(info.getId());
            mContacts.setNickname(info.getNickName());
        }

        if (mContacts == null) {
            ToastUtil.showMessage(R.string.contact_none);
            return;
        }
        CCPAppManager.startChattingAction(this, mContacts.getContactid(), mContacts.getNickname(), true);
    }

    @Override
    public void onItemLongClick(final int position) {
        ECAlertDialog buildAlert = ECAlertDialog.buildAlert(MyPartnersActivity.this, R.string.delete, null, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                RequestParams params = new RequestParams();
                params.put("friendAccount", "" + mResultList.get(position).getAccountName());
                iCommonRequestPresenter.request(ApiConstants.EventTags.FRIEND_DEL, mContext, ApiConstants.Urls.FRIEND_DEL, params);
            }

        });
        buildAlert.setTitle("   ");
        buildAlert.show();
    }

    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }

    @OnClick({R.id.default_layout, R.id.name_layout, R.id.gender_layout, R.id.country_layout, R.id.age_layout, R.id.language_layout})
    public void onClick(View view) {
        setDefaultLayout();
        switch (view.getId()) {
            case R.id.default_layout:
                defalutSelectImg.setVisibility(View.VISIBLE);
                defalutSelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Default");
                orderBy = "";
                descAsc="";
                break;
            case R.id.name_layout:
                nameSelectImg.setVisibility(View.VISIBLE);
                nameSelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Name");
                orderBy = "nick_name";
                descAsc="asc";
                break;
            case R.id.gender_layout:
                genderSelectImg.setVisibility(View.VISIBLE);
                genderSelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Gender");
                orderBy = "gender";
                descAsc="";
                break;
            case R.id.country_layout:
                countrySelectImg.setVisibility(View.VISIBLE);
                countrySelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Country");
                orderBy = "country";
                descAsc="";
                break;
            case R.id.age_layout:
                ageSelectImg.setVisibility(View.VISIBLE);
                ageSelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Age");
                orderBy = "age";
                descAsc="asc";
                break;
            case R.id.language_layout:
                languageSelectImg.setVisibility(View.VISIBLE);
                languageSelectTv.setTextColor(getResources().getColor(R.color.voice_green));
                groupByTv.setText("Language");
                orderBy = "native_language";
                descAsc="";
                break;
        }
        selectLayout.setVisibility(View.GONE);
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(true);
                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }

    }

    private void setDefaultLayout() {
        defalutSelectImg.setVisibility(View.INVISIBLE);
        defalutSelectTv.setTextColor(getResources().getColor(R.color.normal_bg));

        nameSelectImg.setVisibility(View.INVISIBLE);
        nameSelectTv.setTextColor(getResources().getColor(R.color.normal_bg));

        genderSelectImg.setVisibility(View.INVISIBLE);
        genderSelectTv.setTextColor(getResources().getColor(R.color.normal_bg));

        countrySelectImg.setVisibility(View.INVISIBLE);
        countrySelectTv.setTextColor(getResources().getColor(R.color.normal_bg));

        ageSelectImg.setVisibility(View.INVISIBLE);
        ageSelectTv.setTextColor(getResources().getColor(R.color.normal_bg));

        languageSelectImg.setVisibility(View.INVISIBLE);
        languageSelectTv.setTextColor(getResources().getColor(R.color.normal_bg));
    }
}
